package com.sdy.resdir.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.biz.model.TpApproveFlow;
import com.sdy.approval.biz.model.TpOrder;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.common.model.FileObj;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.service.FileService;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.service.*;
import com.sdy.resdir.biz.vo.CatalogVO;
import com.sdy.usercenter.api.UserQueryApi;

import com.sdy.usercenter.api.dto.UserDTO;
import io.swagger.annotations.*;

import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sdy.mvc.controller.BaseController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 未上线资源申请上线
 * </p>
 *
 * @author cgj
 * @since 2019-11-13
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@Api(tags = "未上线资源申请")
@RequestMapping("/rdResForOnline")
public class RdResForOnlineController extends BaseController {
    @Autowired
    private RdResForOnlineService rdResForOnlineService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private RdImplementationOrderService rdImplementationOrderService;
    @Autowired
    private FsApi fsApi;
    @Autowired
    private RdResDetailsApiService rdResDetailsApiService;
    @Autowired
    private RdResDataItemService rdResDataItemService;
    @Autowired
    private RdResourceDirDataService rdResourceDirDataService;
    @Autowired
    private RdDbDictService rdDbDictService;
    @Autowired
    private FileService fileService;
    @Value("${res.app.code}")
    private String appCode;

    public static String randomNum() {
        // 获取随机申请订单
        long dateEx = System.currentTimeMillis();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeEx = dateFormat.format(dateEx);
        int aEx = (int) (Math.random() * 900 + 100);
        String randomThree = Integer.toString(aEx);
        String randomNum = timeEx + randomThree;
        return randomNum;
    }

    @ApiOperation("流程配置模板接口（未上线）")
    @PostMapping("/addApprovalConfigNotOnLine")
    public Response<Boolean> addApprovalConfigNotOnLine(HttpServletRequest request,
                                                        @RequestBody @ApiParam(name = "deptId & resId & resPower",
                                                                value = "部门id，资源id，配置类型") Map<String, Object> map) throws Exception {
        // 拒绝重复发布
        Integer resId = (Integer) map.get("resId");
        Integer isRelease = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId)).getIsRelease();
        Assert.isTrue(isRelease == 1, "该资源已发布，请勿重新发布！");
        // 准备需要的数据
        Integer userId = ssoService.getUserId(request);
        Date date = new Date();
        // (0:发布按钮 1：编辑按钮)
        Boolean aBoolean = rdResForOnlineService.addConfigForOnline(map, date, userId, 0);
        Assert.notTrue(aBoolean, "发布失败！");
        return Response.success();
    }

    @ApiOperation(value = "单条资源立即申请(未上线)", response = RdResourceApplicationDetail.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "选中的资源id")
    })
    @GetMapping("/selectApplyOnlineOne")
    public Response selectApplyOnlineOne(Integer id, HttpServletRequest request) throws BizException {
        // 判断该资源是否有编目信息，没有则不能申请
        RdResourceDir rdResourceDir = rdResourceDirService.getById(id);
        Assert.isNull(rdResourceDir, "无法资源该资源信息");
        UserInfo userInfo = ssoService.getUserInfo(request);
        UserDTO user = userQueryApi.getUser(userInfo.getUserId());
        rdResourceDir.setApplyDeptName(user.getOwnDeptName());
        List<RdDbDict> rdDbDictList = rdDbDictService.list(new LambdaQueryWrapper<RdDbDict>().eq(RdDbDict::getDeptId, user.getOwnDeptId()));
        if (rdResourceDir.getResType() == 1) {
            CatalogVO catalogVO = new CatalogVO();
            RdResDetailsApi rdResDetailsApi = rdResDetailsApiService.getOne(new LambdaQueryWrapper<RdResDetailsApi>().in(RdResDetailsApi::getResDirId, rdResourceDir.getId()));
            Assert.isNull(rdResDetailsApi, "该资源无编目信息");
            catalogVO.setDeptId(rdResourceDir.getResSourceDeptId());
            catalogVO.setDeptName(rdResourceDir.getResSourceDept());
            catalogVO.setRdResDetailsApi(rdResDetailsApi);
            rdResourceDir.setCatalogVO(catalogVO)
                    .setRdDbDictList(rdDbDictList)
                    .setApplyDeptId(user.getOwnDeptId())
                    .setUploadUrl(fileService.getFsUploadAddr())
                    .setApplyDeptName(user.getOwnDeptName());
        } else if (rdResourceDir.getResType() == 2 || rdResourceDir.getResType() == 3) {
            rdResourceDir.setRdDbDictList(rdDbDictList);
            List<RdResDataItem> rdResDataItems = rdResDataItemService.list(new LambdaQueryWrapper<RdResDataItem>().eq(RdResDataItem::getOwnResId, id));
            Assert.isTrue(rdResDataItems.isEmpty(), "该资源无编目信息");
            CatalogVO catalogVO = new CatalogVO();
            catalogVO.setDeptId(rdResourceDir.getResSourceDeptId());
            catalogVO.setDeptName(rdResourceDir.getResSourceDept());
            catalogVO.setRdResDataItemList(rdResDataItems);
            rdResourceDir.setCatalogVO(catalogVO)
                    .setRdDbDictList(rdDbDictList)
                    .setApplyDeptId(user.getOwnDeptId())
                    .setUploadUrl(fileService.getFsUploadAddr())
                    .setApplyDeptName(user.getOwnDeptName());
        }
        // 排除资源的重复申请
        List<RdResForOnline> listOnline = rdResForOnlineService.list(Wrappers.<RdResForOnline>lambdaQuery()
                .eq(RdResForOnline::getResId, id)
                .eq(RdResForOnline::getApplyUserId, ssoService.getUserId(request))
                .in(RdResForOnline::getState, 2, 3, 4, 6));
        Assert.isTrue(!listOnline.isEmpty(), "存在重复申请的资源");
        // 查询资源信息
        return Response.success(rdResourceDir);
    }

    @ApiOperation(value = "立即申请", response = RdResourceApplicationDetail.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "resIdList", value = "选中的资源id（主键）")
    })
    @GetMapping("/selectResBatch")
    public Response<List<RdResourceDir>> selectResBatch(List<Integer> resIdList) throws BizException {
        Assert.isTrue(!StringUtil.isNotBlank(resIdList), "必须选中资源");

        // 排除重复申请资源
        List<RdResForOnline> listOnline = rdResForOnlineService.list(Wrappers.<RdResForOnline>lambdaQuery()
                .in(RdResForOnline::getId, resIdList).eq(RdResForOnline::getState, 3).isNull(RdResForOnline::getVersionNum));
        Assert.notTrue(listOnline.size() == 0, "对不起！该资源已在上线审批中，请耐心等待！");

        // 查询提交的资源信息
        List<RdResourceDir> listDir = rdResourceDirService.list(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resIdList));
        return Response.success(listDir);
    }

    @ApiOperation("单条资源直接申请上线(提交申请)")
    @PostMapping("/oneApplyForOnline")
    public Response<Boolean> oneApplyForOnline(HttpServletRequest request,
                                               @RequestBody @ApiParam(name = "RdResForOnline", value = "实体类（表单数据，提交的资源数据放到实体里的resId")
                                                       RdResForOnline rdResForOnline) throws BizException {
        // 准备需要的数据
        String randomNum = randomNum();
        Integer userId = ssoService.getUserId(request);
        Integer resId = rdResForOnline.getIdList().get(0);
        // 拒绝多余申请
        RdResForOnline oneOtherApply = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery().eq(RdResForOnline::getResId, resId)
                .in(RdResForOnline::getState, 3, 4, 6)
                .isNull(RdResForOnline::getVersionNum));
        Assert.isTrue(oneOtherApply != null, " 该资源已有他人申请，请耐心等待");
        RdResForOnline oneOnline = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery().eq(RdResForOnline::getResId, resId)
                .eq(RdResForOnline::getApplyUserId, userId).isNull(RdResForOnline::getVersionNum).in(RdResForOnline::getState, 3, 4, 6));
        Assert.notTrue(oneOnline == null, "您已申请过该资源,请勿重复申请");

        // 资源库里获取资源信息
        RdResourceDir oneDir = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId));
        UserDTO user = userQueryApi.getUser(userId);
        // 新增本地订单
        rdResForOnline.setApplicationNum(randomNum + "-" + resId)
                .setResId(resId)
                .setResName(oneDir.getResName())
                .setApplyUserId(userId)
                .setState(3)
                .setApplyDeptName(user.getOwnDeptName())
                .setDeptId(user.getOwnDeptId())
                .setApplyTime(new Date())
                .setResType(oneDir.getResType());
        boolean saveOnline = rdResForOnlineService.save(rdResForOnline);
        Assert.notTrue(saveOnline, "新增本地订单时出错!");
        Integer onlineId = rdResForOnline.getId();

        //提交申请到流程
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order_item_no", randomNum + "-" + resId);
        //准备资源id
        String resIdToApproval = "[资源目录]-未归集" + resId;
        map.put("res_id", resIdToApproval);
        map.put("user_id", userId);
        list.add(map);
        Integer integer = approvalAllApi.lookResId(list);
        if (integer != 1) {
            boolean removeOne = rdResForOnlineService.removeById(onlineId);
            Assert.notTrue(removeOne, "移除冗余的订单出错!");
            return Response.error("请检查该订单是否已发布!");
        }
        return Response.success(saveOnline);
    }

    @ApiOperation(value = "我的资源申请列表(未上线)", response = RdResourceApplicationDetail.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "state", value = "当前状态（0未确认 1未提交、2待审批、3已提交至审批中心、4审批中、5已撤回、6审批通过、7已驳回）"),
            @ApiImplicitParam(name = "startTime", value = "申请时间"),
            @ApiImplicitParam(name = "endTime", value = "申请时间"),
            @ApiImplicitParam(name = "resName", value = "资源名称")
    })
    @GetMapping("/selectMyApplyBatch")
    public Response selectMyApplyBatch(HttpServletRequest request, Page page, Integer state, String startTime, String endTime, String resName, Integer resType) throws UnsupportedEncodingException {

        // 准备需要的数据
        Integer userId = ssoService.getUserId(request);

        LambdaQueryWrapper<RdResForOnline> selectOnline = new LambdaQueryWrapper<>();
        // 没有版本信息
        selectOnline.isNull(RdResForOnline::getVersionNum);
        UserDTO user = userQueryApi.getUser(userId);
        selectOnline.eq(RdResForOnline::getDeptId, user.getOwnDeptId());
        // 订单状态不等于1
        selectOnline.ne(RdResForOnline::getState, 1);
        // 审批状态
        selectOnline.eq(null != state, RdResForOnline::getState, state);
        // 申请日期
        if (StringUtil.isNotBlank(startTime)) {
            selectOnline.ge(RdResForOnline::getApplyTime, DateUtil.getDate(startTime + " 00:00:00",
                    DateUtil.DATETIME_FORMAT));
        }
        if (StringUtil.isNotBlank(endTime)) {
            selectOnline.le(RdResForOnline::getApplyTime, DateUtil.getDate(endTime + " 23:59:59",
                    DateUtil.DATETIME_FORMAT));
        }
        // 资源名称搜索
        resName = URLDecoder.decode(resName, "UTF-8");
        selectOnline.like(StringUtil.isNotBlank(resName) && StringUtil.isNotEmpty(resName),
                RdResForOnline::getResName, resName);
        // 资源类型查询
        selectOnline.eq(resType != null, RdResForOnline::getResType, resType);
        // 倒序输出
        selectOnline.orderByDesc(RdResForOnline::getId);

        IPage pageForOnline = rdResForOnlineService.page(page, selectOnline);
        return Response.success(pageForOnline);
    }

    @ApiOperation("我的资源审批列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "result", value = "我的审批状态(1.未审批 2.已审批)--返回数据中有一个approvalResult(1未审批 2已审批),用于隐藏按钮"),
            @ApiImplicitParam(name = "resName", value = "资源名称"),
            @ApiImplicitParam(name = "resPower", value = "共享方式(1.公开 2.受限)"),
            @ApiImplicitParam(name = "updateFrequency", value = "更新频率  实时1、每小时2、每天3、每月4、每季度5、每半年6、每年7、不更新8，不定时9"),
            @ApiImplicitParam(name = "creatTime", value = "开始时间数据"),
            @ApiImplicitParam(name = "endTime", value = "结束时间数据"),
    })
    @GetMapping("/selectMyApplyNotOnLine")
    public Response selectMyApplyNotOnLine(Page page, HttpServletRequest req, Integer result, String resName, Integer resPower,
                                           Integer updateFrequency, String creatTime, String endTime, String applicationNum, Integer applicantDept) throws BizException, UnsupportedEncodingException {
        // 准备需要的数据
        Integer userId = ssoService.getUserId(req);
        List<Integer> ownDeptIdList = userQueryApi.getUser(userId).getOwnDeptIdList();
        List<Integer> roleIdList = userQueryApi.getUser(userId).getRoleIdList();
        // 所有订单中，哪些是需要我审批的(生成节点的订单)
        List<String> applyNumList = approvalAllApi.selectMyApprovalTable(ownDeptIdList, roleIdList, result, "[资源目录]-未归集");
        if (applyNumList.isEmpty()) {
            return Response.success(new Page().setSize(page.getSize()).setCurrent(page.getCurrent()));
        }
        // 准备数据：拿到更新频率和共享方式符合的资源
        List<RdResourceDir> listDir = rdResourceDirService.list(Wrappers.<RdResourceDir>lambdaQuery()
                .eq(null != updateFrequency, RdResourceDir::getUpdateFrequency, updateFrequency)
                .eq(null != resPower, RdResourceDir::getResPower, resPower));
        List<Integer> collectResId = listDir.stream().map(RdResourceDir::getId).collect(Collectors.toList());
        if (collectResId.isEmpty()) {
            return Response.success(new Page().setSize(page.getSize()).setCurrent(page.getCurrent()));
        }
        // 查询对应的节点信息
        List<TpApproveFlow> tpApproveFlows = approvalAllApi.selectApprovalFlowByNumOrderList(applyNumList, ownDeptIdList, roleIdList);
        LambdaQueryWrapper<RdResForOnline> selectOnline = new LambdaQueryWrapper<>();
        selectOnline.in(!applyNumList.isEmpty(), RdResForOnline::getApplicationNum, applyNumList)
                .isNull(RdResForOnline::getVersionNum);
        // 时间条件搜索
        if (StringUtils.isNotBlank(creatTime)) {
            creatTime = java.net.URLDecoder.decode(creatTime, "UTF-8");
            selectOnline.ge(RdResForOnline::getApplyTime, DateUtil.getDate(creatTime + " 00:00:00", DateUtil.DATETIME_FORMAT));
        }
        if (StringUtils.isNotBlank(endTime)) {
            endTime = java.net.URLDecoder.decode(endTime, "UTF-8");
            selectOnline.le(RdResForOnline::getApplyTime, DateUtil.getDate(endTime + " 23:59:59", DateUtil.DATETIME_FORMAT));
        }
        // 订单号模糊搜索
        applicationNum = URLDecoder.decode(applicationNum, "UTF-8");
        selectOnline.like(StringUtil.isNotBlank(applicationNum), RdResForOnline::getApplicationNum, applicationNum);
        // 申请部门筛选
        selectOnline.eq(null != applicantDept, RdResForOnline::getDeptId, applicantDept);
        // 名称搜索
        resName = URLDecoder.decode(resName, "UTF-8");
        selectOnline.like(StringUtil.isNotBlank(resName), RdResForOnline::getResName, resName);
        // 符合更新频率和共享方式
        selectOnline.in(RdResForOnline::getResId, collectResId);
        // 已撤回的订单不显示
        selectOnline.ne(RdResForOnline::getState, 5);
        // 隐藏带有版本的订单
        selectOnline.isNull(RdResForOnline::getVersionNum);
        // 按时间倒序
        selectOnline.orderByDesc(RdResForOnline::getApplyTime);
        IPage ipageData = rdResForOnlineService.page(page, selectOnline);
        List<RdResForOnline> pageData = ipageData.getRecords();
        if (pageData.isEmpty()) {
            return Response.success(new Page().setSize(page.getSize()).setCurrent(page.getCurrent()));
        }
        List<String> applicationNums = pageData.stream().map(RdResForOnline::getApplicationNum).collect(Collectors.toList());
        Assert.isTrue(applicationNums.isEmpty(), "无法获取订单信息，请联系管理员");
        // 所有当前节点信息
        List<Integer> currentFlowLinks = approvalAllApi.selectCurrentFlowLinkList(applicationNums, ownDeptIdList, roleIdList, "[资源目录]-未归集");
        List<Integer> resIds = pageData.stream().map(RdResForOnline::getResId).distinct().collect(Collectors.toList());
        List<RdResourceDir> rdResourceDirs = rdResourceDirService.list(new LambdaQueryWrapper<RdResourceDir>()
                .in(RdResourceDir::getId, resIds));
        Assert.isTrue(rdResourceDirs.isEmpty(), "无法获取资源信息，请联系管理员");
        for (int i = 0; i < pageData.size(); i++) {
            RdResForOnline online = pageData.get(i);
            // 当前登录角色是否可预选资源类型 1 可以 2 不可以
            for (int j = 0; j < rdResourceDirs.size(); j++) {
                // 如果订单资源id=资源id，判断是否可预选
                if (pageData.get(i).getResId().equals(rdResourceDirs.get(j).getId())) {
                    // 资源权限
                    Integer resPowers = rdResourceDirs.get(j).getResPower();
                    // 当前节点
                    Integer currentFlowLink = currentFlowLinks.get(i);
                    online.setResPower(rdResourceDirs.get(j).getResPower());
                    // 如果当前节点是最后一个节点，预选资源类型
                    if (resPowers.equals(currentFlowLink)) {
                        online.setPreselectRes(1);
                    } else {
                        online.setPreselectRes(0);
                    }
                }
            }
            // 每条记录插入对应的部门名称
            for (TpApproveFlow flow : tpApproveFlows) {
                if (online.getApplicationNum().equals(flow.getApplyId())) {
                    online.setApprovalResult(flow.getResult());
                }
            }
        }
        return Response.success(ipageData);
    }

    @ApiOperation("申请单详情(未上线)")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id(主键)", value = "订单数据的id"),
    })
    @GetMapping("/selectOnlineDetail")
    public Response selectOnlineDetail(Integer id, boolean implementationOrderOrNot, HttpServletRequest request) throws BizException {

        HashMap<Object, Object> param = new HashMap<>(16);
        // 基础信息
        RdResForOnline oneOnline = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery().eq(RdResForOnline::getId, id));
        // 准备数据
        Integer userId = ssoService.getUserId(request);
        String deptName = oneOnline.getApplyDeptName();
        String applicationNum = oneOnline.getApplicationNum();
        String userName = userQueryApi.getUser(oneOnline.getApplyUserId()).getName();
        List<Integer> ownDeptIdList = userQueryApi.getUser(userId).getOwnDeptIdList();
        List<Integer> roleIdList = userQueryApi.getUser(userId).getRoleIdList();
        // 订单基础信息查询
        TpApproveFlow tpApproveFlow = approvalAllApi.selectApprovalFlowResultByResId(applicationNum, ownDeptIdList, roleIdList);

        // 插入该节点我的审批结果
        if (null == tpApproveFlow) {
            oneOnline.setApplyDeptName(deptName).setApplyUserName(userName);
        } else if (tpApproveFlow.getResult() == 1) {
            oneOnline.setApplyDeptName(deptName).setApprovalResult(1).setApplyUserName(userName);
        } else {
            oneOnline.setApplyDeptName(deptName).setApprovalResult(2).setApplyUserName(userName);
        }
        String enclosures = oneOnline.getEnclosure();
        if (!"".equals(enclosures) && enclosures != null) {
            String[] enclosureList = enclosures.split(",");
            List<FileObj> fileListInfo = fsApi.getFileListInfo(Arrays.asList(enclosureList));
            oneOnline.setFileInfo(fileListInfo);
        }
        param.put("onlineParam", oneOnline);

        // 节点信息查询
        List<TpApproveFlow> tpApproveFlows = approvalAllApi.selectApprovalFlowByResId(applicationNum);
        param.put("flowParam", tpApproveFlows);

        // 实施工单信息带出
        RdImplementationOrder oneOrder = rdImplementationOrderService.getOne(Wrappers.<RdImplementationOrder>lambdaQuery()
                .eq(RdImplementationOrder::getApplyNum, applicationNum));
        if (oneOrder != null && (oneOrder.getImplementationState() == 1 || oneOrder.getImplementationState() == 2 || oneOrder.getImplementationState() == 3 || oneOrder.getImplementationState() == 4)) {
            oneOrder.setFinishDeptName(userQueryApi.getUser(oneOrder.getFinishUserid()).getOwnDeptName());
        }
        param.put("oneOrderParam", oneOrder);

        // 资源信息查询
        Integer resId = oneOnline.getResId();
        RdResourceDir dirById = rdResourceDirService.getById(resId);
        param.put("resDirParam", dirById);
        return Response.success(param);
    }

    @ApiOperation("资源上线审批")
    @PostMapping("/applyToOnline")
    public Response<Boolean> applyToOnline(HttpServletRequest request,
                                           @RequestBody @ApiParam(name = "applicationNum & resId & result & auditOpinion & preselectResType",
                                                   value = "传入订单号，资源id，审核状态 1-未审核 2-通过 3-驳回，审核意见,预选资源类型") Map<String, Object> map) throws Exception {
        if ((Integer) map.get("result") == 2) {
            boolean updateResType = rdResourceDirService.update(new LambdaUpdateWrapper<RdResourceDir>()
                    .eq(RdResourceDir::getId, map.get("resId"))
                    .set(RdResourceDir::getPreselectResType, map.get("preselectResType")));
            Assert.notTrue(updateResType, "更新资源预选类型失败，请联系管理员");
        }
        // 准备需要的数据
        String applyNum = (String) map.get("applicationNum");
        Integer userId = ssoService.getUserId(request);
        List<Integer> ownDeptIdList = userQueryApi.getUser(userId).getOwnDeptIdList();
        List<Integer> roleIdList = userQueryApi.getUser(userId).getRoleIdList();
        TpApproveFlow tpApproveFlow = new TpApproveFlow();
        tpApproveFlow.setApplyId(applyNum)
                .setResId("[资源目录]-未归集" + map.get("resId"))
                .setResult((Integer) map.get("result"))
                .setAuditOpinion((String) map.get("auditOpinion"))
                .setUserId(userId);
        approvalAllApi.updateNodeApprovalResults(tpApproveFlow, ownDeptIdList, roleIdList);

        // 审批成功后，驳回产生历史版本
        if ((Integer) map.get("result") == 3) {
            // 查询原数据
            LambdaQueryWrapper<RdResForOnline> selectOnline = new LambdaQueryWrapper<>();
            selectOnline.eq(RdResForOnline::getApplicationNum, applyNum)
                    .isNull(RdResForOnline::getVersionNum);
            RdResForOnline oneOnline = rdResForOnlineService.getOne(selectOnline);
            Integer id = oneOnline.getId();
            // 更新原数据
            // 获得最大的版本号
            LambdaQueryWrapper<RdResForOnline> selectOnlineAll = new LambdaQueryWrapper<>();
            selectOnlineAll.eq(RdResForOnline::getApplicationNum, applyNum).isNotNull(RdResForOnline::getVersionNum);
            List<RdResForOnline> onlineAll = rdResForOnlineService.list(selectOnlineAll);
            List<Integer> versionList = onlineAll.stream().map(RdResForOnline::getVersionNum).collect(Collectors.toList());
            Integer versionMax = 0;
            if (versionList.isEmpty()) {
                versionMax = 1;
            } else {
                versionMax = Collections.max(versionList) + 1;
            }
            // 新增一条新的原数据
            boolean saveDetail = rdResForOnlineService.save(oneOnline.setState(7));
            // 把原数据改为驳回并加上版本
            LambdaUpdateWrapper<RdResForOnline> upOnline = new LambdaUpdateWrapper<>();
            upOnline.eq(RdResForOnline::getId, id)
                    .set(RdResForOnline::getState, 7)
                    .set(RdResForOnline::getVersionNum, versionMax)
                    .set(RdResForOnline::getModifyTime, new Date());
            boolean updateOnline = rdResForOnlineService.update(upOnline);
            if (!updateOnline || !saveDetail) {
                log.info("新增版本数据出错");
                return Response.error();
            }
        }
        return Response.success();
    }

    @ApiOperation("修改申请内容(未上线)")
    @PostMapping("/updateApplyOnline")
    public Response<Boolean> updateApplyOnline(HttpServletRequest request,
                                               @RequestBody @ApiParam(name = "RdResForOnline", value = "实体类(一定要放入该订单的主键id)")
                                                       RdResForOnline rdResForOnline) throws BizException {
        // 准备需要的数据
        RdResForOnline oneOnline = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery()
                .eq(RdResForOnline::getId, rdResForOnline.getId()));
        String applicationNum = oneOnline.getApplicationNum();
        // 判断是否被人修改过
        Integer state = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery()
                .eq(RdResForOnline::getApplicationNum, applicationNum).isNull(RdResForOnline::getVersionNum)).getState();
        Assert.isTrue(state != 7, "该订单已被他人修改,请您刷新数据!");
        Integer resId = oneOnline.getResId();
        Integer isRelease = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId)).getIsRelease();
        Assert.isTrue(isRelease == 0, "该资源已下架,暂不支持提交！");
        Integer userId = ssoService.getUserId(request);
        rdResForOnline.setModifyTime(new Date())
                .setModifyUserId(userId);
        // 查询当前订单
        List<TpOrder> orders = approvalAllApi.selectOrderByApplyNum(applicationNum, 1);
        // 拿到该订单的状态
        Integer gsOrderState = orders.get(0).getGsOrderState();
        if (gsOrderState == 3) {
            boolean updateOnline = rdResForOnlineService.updateById(rdResForOnline);
            Assert.notTrue(updateOnline, "修改本地订单时出现错误");
        } else if (gsOrderState == 4) {
            return Response.error("该订单正在审批中,请勿修改!");
        } else if (gsOrderState == 7) {
            boolean updateOnline = rdResForOnlineService.updateById(rdResForOnline.setState(3));
            Assert.notTrue(updateOnline, "修改本地订单出错");
            // 清除冗余数据
            Boolean aBoolean = approvalAllApi.updateFlow(applicationNum, userId);
            Assert.notTrue(aBoolean, "调用approval远程接口时报错");
        }
        return Response.success();
    }

    @ApiOperation("历史版本信息查询(未上线)")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "applyNum", value = "订单号"),
            @ApiImplicitParam(name = "versionNum", value = "版本号")
    })
    @GetMapping("/selectNotOnlineHistory")
    public Response selectNotOnlineHistory(String applyNumChild, Integer versionNum, HttpServletRequest req) {
        // 查询未上线资源申请历史
        RdResForOnline oneOnlineHistory = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery()
                .eq(StringUtil.isNotEmpty(applyNumChild), RdResForOnline::getApplicationNum, applyNumChild)
                .eq(versionNum != null, RdResForOnline::getVersionNum, versionNum));
        HashMap<Object, Object> param = new HashMap<>();

        // 资源信息查询
        Integer resId = oneOnlineHistory.getResId();
        LambdaQueryWrapper<RdResourceDir> selectDir = new LambdaQueryWrapper<>();
        selectDir.eq(resId != null, RdResourceDir::getId, resId);
        RdResForOnline rdResForOnline = rdResForOnlineService.getOne(new LambdaQueryWrapper<RdResForOnline>().eq(RdResForOnline::getResId, resId));
        RdResourceDir listDir = rdResourceDirService.getOne(selectDir);
        if (rdResForOnline != null && listDir != null) {
            listDir.setEnclosure(rdResForOnline.getEnclosure());
        }
        param.put("dirParam", listDir);

        // 申请信息查询
        String userName = userQueryApi.getUser(oneOnlineHistory.getApplyUserId()).getName();
        String deptName = userQueryApi.getDept(oneOnlineHistory.getDeptId()).getName();
        // 插入申请人部门名称&申请人名称
        oneOnlineHistory.setApplyDeptName(deptName).setApplyUserName(userName);
        // 相关文件数据
        List<FileObj> fileObjs = new ArrayList<>();
        String enclosures = oneOnlineHistory.getEnclosure();
        if (!"".equals(enclosures) && enclosures != null) {
            String[] enclosureList = enclosures.split(",");
            List<FileObj> fileListInfo = fsApi.getFileListInfo(Arrays.asList(enclosureList));
            oneOnlineHistory.setFileInfo(fileListInfo);
        }
        param.put("onlineParam", oneOnlineHistory);

        // 实施工单信息
        RdImplementationOrder oneOrder = rdImplementationOrderService.getOne(Wrappers.<RdImplementationOrder>lambdaQuery()
                .eq(RdImplementationOrder::getApplyNum, applyNumChild));
        param.put("orderParam", oneOrder);
        return Response.success(param);
    }

}
